<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑房户' : '新增房户'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="房户编号" prop="householdCode">
        <el-input
          v-model="formData.householdCode"
          placeholder="请输入房户编号"
          maxlength="50"
          show-word-limit
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="formData.roomNumber"
          placeholder="请输入房间号"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="所属社区" prop="communityId">
        <el-select
          v-model="formData.communityId"
          placeholder="请选择所属社区"
          style="width: 100%"
          clearable
          :disabled="isEdit"
          @change="handleCommunityChange"
        >
          <el-option
            v-for="item in communityOptions"
            :key="item.id"
            :label="item.communityName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="所属楼栋" prop="buildingId">
        <el-select
          v-model="formData.buildingId"
          placeholder="请选择所属楼栋"
          style="width: 100%"
          clearable
          :disabled="isEdit || !formData.communityId"
          @change="handleBuildingChange"
        >
          <el-option
            v-for="item in buildingOptions"
            :key="item.id"
            :label="item.buildingName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="所属单元" prop="unitId">
        <el-select
          v-model="formData.unitId"
          placeholder="请选择所属单元"
          style="width: 100%"
          clearable
          :disabled="isEdit || !formData.buildingId"
        >
          <el-option
            v-for="item in unitOptions"
            :key="item.id"
            :label="item.unitName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="楼层号" prop="floorNumber">
        <el-input-number
          v-model="formData.floorNumber"
          :min="1"
          :max="100"
          placeholder="请输入楼层号"
          style="width: 100%"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="房屋面积" prop="area">
        <el-input-number
          v-model="formData.area"
          :min="1"
          :max="1000"
          :precision="2"
          placeholder="请输入房屋面积"
          style="width: 100%"
        />
        <span class="unit-text">平方米</span>
      </el-form-item>
      
      <el-form-item label="使用面积" prop="usableArea">
        <el-input-number
          v-model="formData.usableArea"
          :min="1"
          :max="1000"
          :precision="2"
          placeholder="请输入使用面积"
          style="width: 100%"
        />
        <span class="unit-text">平方米</span>
      </el-form-item>
      
      <el-form-item label="朝向" prop="orientation">
        <el-select
          v-model="formData.orientation"
          placeholder="请选择朝向"
          style="width: 100%"
        >
          <el-option label="东" value="东" />
          <el-option label="南" value="南" />
          <el-option label="西" value="西" />
          <el-option label="北" value="北" />
          <el-option label="东南" value="东南" />
          <el-option label="西南" value="西南" />
          <el-option label="东北" value="东北" />
          <el-option label="西北" value="西北" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="房间类型" prop="roomType">
        <el-select
          v-model="formData.roomType"
          placeholder="请选择房间类型"
          style="width: 100%"
        >
          <el-option label="一室" :value="1" />
          <el-option label="两室" :value="2" />
          <el-option label="三室" :value="3" />
          <el-option label="四室及以上" :value="4" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="产权类型" prop="propertyType">
        <el-select
          v-model="formData.propertyType"
          placeholder="请选择产权类型"
          style="width: 100%"
        >
          <el-option label="自有" :value="1" />
          <el-option label="租赁" :value="2" />
          <el-option label="其他" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="房产证号" prop="propertyCertificate">
        <el-input
          v-model="formData.propertyCertificate"
          placeholder="请输入房产证号"
          maxlength="100"
        />
      </el-form-item>
      
      <el-form-item label="购买日期" prop="purchaseDate">
        <el-date-picker
          v-model="formData.purchaseDate"
          type="date"
          placeholder="请选择购买日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item label="物业费单价" prop="propertyFeeRate">
        <el-input-number
          v-model="formData.propertyFeeRate"
          :min="0"
          :max="100"
          :precision="2"
          placeholder="请输入物业费单价"
          style="width: 100%"
        />
        <span class="unit-text">元/平方米</span>
      </el-form-item>
      
      <el-form-item label="房户状态" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择房户状态"
          style="width: 100%"
        >
          <el-option label="空置" :value="0" />
          <el-option label="已入住" :value="1" />
          <el-option label="装修中" :value="2" />
          <el-option label="出租" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="房户描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入房户描述"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 房户信息编辑表单
 * @author Wu.Liang
 * @date 2024-12-21
 */
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { householdApi } from '@/api/household'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { communityApi } from '@/api/community'
import { householdFormRules } from '@/types/region'

// 定义props
interface Props {
  visible: boolean
  formData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: null
})

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref()
const loading = ref(false)
const buildingOptions = ref<any[]>([])
const unitOptions = ref<any[]>([])
const communityOptions = ref<any[]>([])

// 表单数据
const formData = ref({
  householdCode: '',
  roomNumber: '',
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  floorNumber: 1,
  area: 0,
  usableArea: 0,
  orientation: '',
  roomType: 1,
  propertyType: 1,
  propertyCertificate: '',
  purchaseDate: '',
  propertyFeeRate: 0,
  status: 0,
  description: ''
})

// 表单验证规则
const formRules = householdFormRules

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.formData?.id)

// 重置表单 - 移到watch之前定义
const resetForm = () => {
  formData.value = {
    householdCode: '',
    roomNumber: '',
    communityId: undefined as number | undefined,
    buildingId: undefined as number | undefined,
    unitId: undefined as number | undefined,
    floorNumber: 1,
    area: 0,
    usableArea: 0,
    orientation: '',
    roomType: 1,
    propertyType: 1,
    propertyCertificate: '',
    purchaseDate: '',
    propertyFeeRate: 0,
    status: 0,
    description: ''
  }
  unitOptions.value = []
  formRef.value?.clearValidate()
}

// 监听表单数据变化
watch(() => props.formData, async (newData) => {
  if (newData) {
    // 确保数字字段的类型正确
    const processedData = {
      ...newData,
      communityId: newData.communityId != null ? Number(newData.communityId) : undefined,
      buildingId: newData.buildingId != null ? Number(newData.buildingId) : undefined,
      unitId: newData.unitId != null ? Number(newData.unitId) : undefined,
      floorNumber: newData.floorNumber != null ? Number(newData.floorNumber) : 1,
      area: newData.area != null ? Number(newData.area) : 0,
      usableArea: newData.usableArea != null ? Number(newData.usableArea) : 0,
      roomType: newData.roomType != null ? Number(newData.roomType) : 1,
      propertyType: newData.propertyType != null ? Number(newData.propertyType) : 1,
      propertyFeeRate: newData.propertyFeeRate != null ? Number(newData.propertyFeeRate) : 0,
      status: newData.status != null ? Number(newData.status) : 0
    }
    formData.value = processedData
    
    // 编辑模式下，加载楼栋和单元的选项数据
    if (isEdit.value && processedData.communityId) {
      try {
        // 加载楼栋选项
        const buildingResponse = await buildingApi.getBuildingsByCommunity(processedData.communityId)
        buildingOptions.value = (buildingResponse.data || []).filter((item: any) => item.id != null)
        
        // 如果有楼栋ID，加载单元选项
        if (processedData.buildingId) {
          const unitResponse = await unitApi.getUnitsByBuilding(processedData.buildingId)
          unitOptions.value = (unitResponse.data || []).filter((item: any) => item.id != null)
        }
      } catch (error) {
        console.error('加载楼栋或单元数据失败:', error)
      }
    }
    
    // 延迟清除验证错误，确保数据完全加载后再清除
    nextTick(() => {
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 社区变化处理
const handleCommunityChange = async (communityId: number) => {
  formData.value.buildingId = undefined
  formData.value.unitId = undefined
  buildingOptions.value = []
  unitOptions.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      // 过滤掉没有有效id的数据
      buildingOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      ElMessage.error({ message: '加载楼栋数据失败' })
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number) => {
  formData.value.unitId = undefined
  unitOptions.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      // 过滤掉没有有效id的数据
      unitOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      ElMessage.error({ message: '加载单元数据失败' })
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    loading.value = true
    
    if (isEdit.value) {
      await householdApi.updateHousehold(props.formData.id, formData.value)
    } else {
      await householdApi.createHousehold(formData.value)
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      ElMessage.error({ message: '操作失败' })
    }
  } finally {
    loading.value = false
  }
}

// 加载社区选项
const loadCommunityOptions = async () => {
  try {
    const response = await communityApi.getCommunityList({})
    // 过滤掉没有有效id的数据
    communityOptions.value = (response.data || []).filter((item: any) => item.id != null)
  } catch (error) {
    ElMessage.error({ message: '加载社区数据失败' })
  }
}

// 加载楼栋选项
const loadBuildingOptions = async () => {
  try {
    // 使用分页接口获取楼栋列表，设置较大的pageSize以获取所有楼栋
    const response = await buildingApi.getBuildingPage({
      pageNum: 1,
      pageSize: 1000 // 设置较大的页面大小以获取所有楼栋
    })
    
    // 从分页响应中提取数据并过滤无效数据
    const buildingList = response.data?.records || response.data || []
    buildingOptions.value = buildingList.filter((item: any) => item.id != null)
  } catch (error) {
    console.error('加载楼栋数据失败:', error)
    ElMessage.error('加载楼栋数据失败')
    buildingOptions.value = []
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadCommunityOptions()
  loadBuildingOptions()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}
</style> 